import re, binascii, serial, serial.tools.list_ports, datetime



class TZn645:
    def __init__(self):
        self.comPort = 'COM8'
        self.comBaudrate = 1200
        self.comParity = 'E' # serial.PARITY_EVEN ,
        self.comTimeout = 2
        self.serial= serial.Serial()
    def isOpen(self):
        res = False
        try:
            if self.serial!=None:
                res = self.serial.isOpen()
        except Exception as er:
            print(er)
        return  res
    def open(self):
        try:
            if not self.isOpen():
                self.serial = serial.Serial(
                    self.comPort, self.comBaudrate, parity=self.comParity, timeout=self.comTimeout
                )
        except Exception as er:
            print(er)
        return  self.isOpen()

    def close(self):
        try:
            if self.serial!=None:
                if self.serial.isOpen():
                    self.serial.close()
                self.serial = None
        except Exception as er:
            print(er)
    def readValue(self , address , dataFlag):
        status = 0
        res = ''
        try:
            sendBytes = self.getSendBytes(address , dataFlag)
            self.serial.write(sendBytes)
            resBytes = self.serial.readline()
            resBytes = resBytes[resBytes.index(0x68):]

            addrBytes = ["{:0>2d}".format((x//16)*10 + x%16) for x in resBytes[1:7]]
            addrBytes.reverse()
            addr = ''.join(addrBytes)

            dataBytes = ["{:0>2d}".format(int(hex(x-0x33).replace('0x',''))) for x in resBytes[14:-2]]
            dataBytes.reverse()
            res = "".join(dataBytes)

            status = 1
        except Exception as er :
            print(er)
        return  status , res
    def getSendBytes(self , address , dataFlag):
        res=[]
        try:
            res.append(0x68)
            for i in range(6):
                pos = ( 6 - (i+1)) *2
                addr = int(address[pos:pos+2])
                addr = (addr // 10 ) * 16 + addr%10
                res.append(addr)
            res.append(0x68)
            res.append(0x11)
            res.append(0x04)
            for i in range(4):
                di = int(dataFlag[i])  + 0x33
                res.append(di)
            c = 0
            for i in res:
                c = c + i
                c = c % 256
            res.append(c)
            res.append(0x16)
        except Exception as er :
            print(er)
        return  bytearray(res)
'''
zn645 = TZn645()
flag = zn645.open()
print(flag , zn645.serial)

zn645.readValue('001541869457','0020')
zn645.serial.close()
'''